<template>
	<div class="app-container" style="min-width: 1000px">
		<!-- 搜索条件 -->

		<yd-form
			class="yd-form-wraper"
			ref="myForm"
			:options="formOptions"
			:model="formData"
			@form-init="formInited"
			@search="formSearch"
			@change="formModalChange"
		>
			<template #form-btn="props">
				<el-button class="yd-form-btn" type="primary" @click="searchHandler">查询</el-button>
			</template>
		</yd-form>

		<!-- 上方图表 -->

		<el-row style="height: 600px; margin-bottom: 20px">
			<el-col :span="10" style="height: 100%; padding-right: 10px">
				<el-row style="height: 47%">
					<!-- 健康度 -->
					<yd-card>
						<div class="yd-card-header">
							<div class="yd-card-title">
								<span class="yd-circle"></span>
								<span>{{ systemName }}</span>
							</div>
						</div>
						<div class="yd-flex" style="margin-bottom: 10px; padding-top: 30px; height: 84%">
							<div style="flex: 1; height: 100%">
								<div id="systemHealthyRateChartId" v-loading="loading.systemHealthyRateChart" style="height: 100%; width: 100%"></div>
								<!-- <div style="height: 100%"></div> -->
							</div>
							<div style="flex: 1" class="system-health-textBox">
								<div class="vertical-center">
									<el-row class="system-health-item">
										<el-col :span="9">系统请求量：</el-col>
										<el-col :span="12" class="text-white">{{ system.reqCount || 0 }}</el-col>
									</el-row>
									<el-row class="system-health-item">
										<el-col :span="9">告警请求量：</el-col>
										<el-col :span="12">
											<el-link class="text-yellow" @click="handleAlarmValJump(undefined)">{{ system.alarmCount || 0 }}</el-link>
										</el-col>
									</el-row>
									<el-row class="system-health-item">
										<el-col :span="9">失败请求量：</el-col>
										<el-col :span="12">
											<el-link class="text-red" @click="handleAlarmValJump(0)">{{ system.failReqCount || 0 }}</el-link>
										</el-col>
									</el-row>
									<el-row class="system-health-item">
										<el-col :span="9">平均响应时长：</el-col>
										<el-col :span="12" class="text-white">{{ formatter(system.avgDealTime) || 0 }}</el-col>
									</el-row>
									<el-row class="system-health-item">
										<el-col :span="9">当前用户数：</el-col>
										<el-link :span="12" @click="go2UserOperate()" class="text-blue">{{ userNum || 0 }}</el-link>
									</el-row>
									<el-row class="system-health-item">
										<el-col :span="9">异常用户数：</el-col>
										<el-link :span="12" @click="go2UserOperate(1)" class="text-red">{{ exceptionUserNum || 0 }}</el-link>
									</el-row>
								</div>
							</div>
						</div>
					</yd-card>
				</el-row>
				<el-row style="height: 53%">
					<!-- 两个饼图 -->
					<yd-card style="width: 100%; height: 100%">
						<el-row :gutter="10" class="chart-container" style="height: 100%">
							<el-col :span="12" style="height: 100%">
								<div class="alarm-pie-title">告警类型占比</div>
								<div v-loading="loading.alarmTypeProportionChart" id="alarmTypeProportionChartId" style="height: 87%"></div>
							</el-col>
							<el-col :span="12" style="height: 100%">
								<div class="alarm-pie-title">网端告警量占比</div>
								<div v-loading="loading.segmenetAlarmProportionChart" id="segmenetAlarmProportionChartId" style="height: 87%"></div>
							</el-col>
						</el-row>
					</yd-card>
				</el-row>
			</el-col>
			<el-col :span="14" style="height: 100%">
				<!-- 三个趋势图 -->
				<el-row style="height: 33.3%">
					<yd-card>
						<div class="yd-card-header yd-flex">
							<div class="yd-card-title">
								<span class="yd-circle"></span>
								<span>系统请求量</span>
							</div>
							<div class="yd-flex">
								<!-- <p style="margin-right: 15px">
									<span class="color-primary">历史峰值：</span>
									<span>{{ reqPeek.weekAvgValue }}</span>
								</p> -->
								<el-tooltip effect="light" :z-index="9999">
									<span style="z-index: 9999; margin-right: 15px">历史峰值：{{ reqPeek.peakValue }}</span>
									<template #content>
										<p>历史峰值：{{ reqPeek.peakValue }}</p>
										<p>发生时间：{{ reqPeek.peakBeginTime }} - {{ reqPeek.peakEndTime }}</p>
									</template>
								</el-tooltip>
								<el-tooltip effect="light" :z-index="9999">
									<span style="z-index: 9999; margin-right: 15px">月平均值：{{ reqPeek.monthAvgValue }}</span>
									<template #content>
										<p>月平均值：{{ reqPeek.monthAvgValue }}</p>
										<p>发生时间：{{ reqPeek.monthStartTime }} - {{ reqPeek.monthEndTime }}</p>
									</template>
								</el-tooltip>
								<el-tooltip effect="light" :z-index="9999">
									<span style="z-index: 9999; margin-right: 15px">周平均值：{{ reqPeek.weekAvgValue }}</span>
									<template #content>
										<p>周平均值：{{ reqPeek.weekAvgValue }}</p>
										<p>发生时间：{{ reqPeek.weekStartTime }} - {{ reqPeek.weekEndTime }}</p>
									</template>
								</el-tooltip>
							</div>
						</div>
						<div id="systemReqCountTrendChartId" style="height: 84%; width: 100%"></div>
					</yd-card>
				</el-row>
				<el-row style="height: 33.3%">
					<yd-card>
						<div class="yd-card-header">
							<div class="yd-card-title">
								<span class="yd-circle"></span>
								<span>平均响应时长(毫秒)</span>
							</div>
						</div>

						<div id="systemAvgDealTimeTrendChartId" style="height: 84%; width: 100%"></div>
					</yd-card>
				</el-row>
				<el-row style="height: 33.3%">
					<yd-card>
						<div class="yd-card-header">
							<div class="yd-card-title">
								<span class="yd-circle"></span>
								<span>系统健康度(%)</span>
							</div>
						</div>
						<div id="systemHealthRateTrendChartId" style="height: 80%; width: 100%"></div>
					</yd-card>
				</el-row>
			</el-col>
		</el-row>

		<!-- 业务/网端总览列表 -->
		<el-row>
			<el-col :span="14" style="padding-right: 10px">
				<yd-card>
					<el-row class="yd-card-header">
						<el-col :span="16" class="yd-card-title">
							<div class="yd-circle"></div>
							<span>业务总览-{{ systemName }}</span>
						</el-col>
						<el-col :span="7" style="text-align: right">
							<yd-form ref="businessForm" :options="businessFormOptions" :model="formDatas.businessFormData" @change="formModalChange"> </yd-form>
						</el-col>
						<el-col :span="1" style="text-align: center">
							<el-button type="text" :disabled="exportDisable" :loading="downloading" @click="handleBusiExport">
								<svg-icon icon-class="daochu" class="icon-cls"></svg-icon>
							</el-button>
						</el-col>
					</el-row>

					<YdTable
						:formData="formDatas.businessFormData"
						:tableConfig="tableConfigs.businessOverviewConfig"
						:tableData="tableDatas.businessOverviewData"
						@sizeChangeHandler="queryBusinessOverview"
						@currentChangeHandler="queryBusinessOverview"
						@sortChangeHandler="queryBusinessOverview"
					></YdTable>
				</yd-card>
			</el-col>
			<el-col :span="10">
				<yd-card>
					<el-row class="yd-card-header">
						<el-col :span="15">
							<div class="yd-card-title">
								<span class="yd-circle"></span>
								<span> 网端总览-{{ systemName }} </span>
								<el-tooltip effect="light" placement="top-start" style="margin-left: 5px; z-index: 999">
									<template v-slot:content>网端监控详情暂不支持跨天查询</template>
									<svg-icon icon-class="question" class="yd-card-title-icon"></svg-icon>
								</el-tooltip>
							</div>
						</el-col>
						<el-col :span="8">
							<yd-form ref="segmentForm" :options="segmentFormOptions" :model="formDatas.segmentFormData" @change="formModalChange"> </yd-form>
						</el-col>
						<el-col :span="1" style="text-align: center">
							<el-button type="text" :disabled="exportDisable1" :loading="downloading1" @click="handleExportSegment">
								<svg-icon icon-class="daochu" class="icon-cls"></svg-icon>
							</el-button>
						</el-col>
					</el-row>
					<YdTable
						:form-data="formDatas.segmentFormData"
						:table-config="tableConfigs.segmentOverviewConfig"
						:table-data="tableDatas.segmentOverviewData"
						@sizeChangeHandler="querySegmentOverview"
						@currentChangeHandler="querySegmentOverview"
						@sortChangeHandler="querySegmentOverview"
					></YdTable>
				</yd-card>
			</el-col>
		</el-row>
	</div>
</template>
<script lang="tsx" setup name="business-monitor-system-detail">
import { ref, reactive, onMounted, getCurrentInstance, onActivated, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import * as echarts from 'echarts';
import 'echarts-liquidfill';
import { toDecimalFormate, downloadFromBlob } from '@/utils/common';
import { cockpitChartStyle, noDataOption } from '@/utils/defaultChartConfig';
// import { queryAppSystemOptions, querySegmentBySystemId } from '@/api/search/searchOptions';
import { querySystemStatisticsDetail, queryUserNum, queryExceptionUserNum, querySystemTrendList } from '@/api/bpm/system/app_system';
import { queryAlarmProportion } from '@/api/bpm/alarm/alarm_type';
import { querySegmentAlarmProportion, querySegmentDataOverview, exportSegmentList } from '@/api/bpm/segment/segment_overview';
import { queryBusinessOverviewListPage, exportBusinessList } from '@/api/bpm/business/business_overview';
import { resizeMixins } from '@/mixins/resize';
// import YdTable from '@/components/YdTable/index.vue';
import YdForm from '@/components/YdForm/index.vue';

const instance = getCurrentInstance();
const proxy = instance?.proxy;

const route = useRoute();
const router = useRouter();

const myForm = ref<InstanceType<typeof YdForm>>();
const businessForm = ref<InstanceType<typeof YdForm>>();
const segmentForm = ref<InstanceType<typeof YdForm>>();

// 查询参数
let formData = reactive<FormModelType>({});

// option
const systemHealthyRateOption = ref();

// 历史峰值
let reqPeek = ref<anyObj>({});

// 系统下拉
const systemOptions = ref([]);
const firstFlag = ref(true);
const systemName = ref('');
const systemTempName = ref('');
// 业务下拉
const businessOptions = ref([]);
// 网端下拉
const segmentOptions = ref([]);
// 导出步骤按钮
const downloading = ref(false);
const exportDisable = ref(false);
const downloading1 = ref(false);
const exportDisable1 = ref(false);
const downloadStartTime = ref('');
const downloadEndTime = ref('');
const selectValue = ref('');

const labelTimeArr = ref([]);

const selectSystemId = ref(null);
// 统一图表样式
const chartStyle = cockpitChartStyle();

// 图表对象
const chart: anyObj = {
	systemHealthyRateChart: null,
	alarmTypeProportionChart: null,
	segmenetAlarmProportionChart: null,
	systemReqCountTrendChart: null,
	systemAvgDealTimeTrendChart: null,
	systemHealthRateTrendChart: null,
};

const formOptions = ref<FormOptionType>([
	{
		type: 'select',
		label: '业务系统',
		prop: 'systemId',
		api: {
			name: 'queryAppSystemOptions',
			params: { isStatus: 1 },
		},
	},
	{
		type: 'date-picker',
		label: '时间范围',
		prop: 'dateRange',
		span: 8,
		dateType: 'datetimerange',
		// shortcutsKeys: ['last1h', 'today', 'lastDay'],
		// defaulShortcutsKey: 'lastlh',
	},
]);

// 业务

const businessFormOptions = ref<FormOptionType>([
	{
		type: 'select',
		label: '',
		prop: 'businessCodeList',
		span: 24,
		placeholder: '请选择业务名称',
		isInitOption: false,
		api: {
			name: 'queryBusinessOptions',
		},
		// cascaderParam: {
		// 	data: formData,
		// 	key: 'systemId',
		// },
		attrs: {
			multiple: true,
		},
	},
]);
// 网端
const segmentFormOptions = ref<FormOptionType>([
	{
		type: 'select',
		label: '',
		prop: 'segmentIdList',
		span: 24,
		placeholder: '请选择网端',
		isInitOption: false,
		api: {
			name: 'querySegmentOptions',
		},
		// cascaderParam: {
		// 	data: formData,
		// 	key: 'systemId',
		// },
		attrs: {
			multiple: true,
		},
	},
]);

// 搜索表单数据
const formDatas = reactive<Record<string, FormModelType>>({
	businessFormData: {
		businessCodeList: [],
		orderByColumn: 'healthRate',
		isAsc: 'asc',
		pageSize: 10,
		pageNum: 1,
	},
	segmentFormData: {
		segmentIdList: [],
		orderByColumn: 'healthRate',
		isAsc: 'asc',
		pageSize: 10,
		pageNum: 1,
	},
});

// 当前页面选择的系统
const userNum = ref(0);
const exceptionUserNum = ref(0);
let system = ref({});
// 加载层
const loading = reactive({
	systemHealthyRateChart: false,
	alarmTypeProportionChart: false,
	segmenetAlarmProportionChart: false,
});
// 选中的系统Id

// 列表配置
const tableConfigs = reactive<Record<string, TableConfigType>>({
	// 业务总览列表配置
	businessOverviewConfig: {
		columns: [
			{
				label: '业务名称',
				prop: 'businessName',
				operation: [
					{
						text: undefined,
						rowKey: 'businessName',
						handler: (scope: any) => {
							let systemId =  scope.row.systemId;
							systemId = systemId ? String(systemId) : systemId;
							router.push({
								path: '/business-monitor/monitor/business-detail/index',
								query: {
									data: JSON.stringify({
										systemId: systemId,
										businessCode: scope.row.businessCode,
										startTime: formData.startTime,
										endTime: formData.endTime,
									}),
								},
							});
						},
					},
				],
			},
			{
				label: '访问量',
				prop: 'visitCount',
				sortable: true,
			},
			{
				label: '交易量',
				prop: 'completeVisitCount',
				sortable: true,
			},
			{
				label: '平均响应耗时',
				prop: 'serverAvgResponseTime',
				sortable: true,
				width: 130,
				formatter(row: any, val: any) {
					return toDecimalFormate(val, 'wm');
				},
			},
			{
				label: '失败数',
				prop: 'failVisitCount',
				sortable: true,
				operation: [
					{
						rowKey: 'failVisitCount',
						color: '#fe5578',
						handler: (scope: any) => {
							let systemId =  scope.row.systemId;
							systemId = systemId ? String(systemId) : systemId;
							let data = JSON.stringify({
								systemId: systemId,
								startTime: formData.startTime,
								endTime: formData.endTime,
								businessCodeList: [scope.row.businessCode],
								dealState: 0,
							});
							router.push({
								path: '/business-monitor/monitor-query/business-list',
								query: {
									data,
								},
							});
						},
					},
				],
			},
			{
				label: '告警数',
				prop: 'alarmVisitCount',
				sortable: true,
				operation: [
					{
						rowKey: 'alarmVisitCount',
						color: '#ff9a0c',
						handler: (scope: any) => {
							let systemId =  scope.row.systemId;
							systemId = systemId ? String(systemId) : systemId;
							let data = JSON.stringify({
								systemId: systemId,
								startTime: formData.startTime,
								endTime: formData.endTime,
								businessCodeList: [scope.row.businessCode],
								isAlarm: 1,
							});
							router.push({
								path: '/business-monitor/monitor-query/business-list',
								query: {
									data,
								},
							});
						},
					},
				],
			},
			{
				label: '成功率',
				prop: 'successRate',
				formatter(row: any, val: any) {
					return val + '%';
				},
				sortable: true,
			},
			{
				label: '健康度',
				prop: 'healthRate',
				sortable: true,
				renderXss: (row: any, val: any) => {
					if (val >= 90) {
						return <span style="color: #30B08F">{val + '%'}</span>;
					} else if (val >= 70) {
						return <span style="color: #FEC171">{val + '%'}</span>;
					} else {
						return <span style="color: #C03639">{val + '%'}</span>;
					}
				},
			},
		],
		pagination: {
			pageNum: 1,
			// orderByColumn: 'visitCount',
			// isAsc: 'desc',
			// total: 0,
		},
		loading: false,
		disableOrderNumber: false,
	},
	// 网端总览列表配置
	segmentOverviewConfig: {
		columns: [
			{
				label: '网端名称',
				prop: 'segmentName',
				operation: [
					{
						text: undefined,
						rowKey: 'segmentName',
						handler: (scope: any) => {
							router.push({
								path: '/business-monitor/monitor/network-detail/index',
								query: {
									data: JSON.stringify({
										systemId: selectSystemId.value,
										startTime: formData.startTime,
										endTime: formData.endTime,
										segmentName: scope.row.segmentName,
										segmentId: scope.row.id,
									}),
								},
							});
						},
					},
				],
			},
			{
				label: '请求总量',
				prop: 'reqCount',
				sortable: true,
			},
			{
				label: '失败请求',
				prop: 'failReqCount',
				sortable: true,
				operation: [
					{
						rowKey: 'failReqCount',
						color: '#fe5578',
						handler: (scope: any) => {
							router.push({
								path: '/business-monitor/monitor-analysis/basic-alarm-merging-analysis',
								query: {
									data: JSON.stringify({
										systemId: selectSystemId.value,
										segmentIds: [scope.row.id],
										startTime: formData.startTime,
										endTime: formData.endTime,
										alarmStates: [0],
									}),
								},
							});
						},
					},
				],
			},
			{
				label: '告警请求',
				prop: 'alarmReqCount',
				sortable: true,
				operation: [
					{
						rowKey: 'alarmReqCount',
						color: '#ff9a0c',
						handler: (scope: any) => {
							router.push({
								path: '/business-monitor/monitor-analysis/basic-alarm-merging-analysis',
								query: {
									data: JSON.stringify({
										systemId: selectSystemId.value,
										segmentIds: [scope.row.id],
										startTime: formData.startTime,
										endTime: formData.endTime,
									}),
								},
							});
						},
					},
				],
			},
			{
				label: '健康度',
				prop: 'healthRate',
				sortable: true,
				renderXss: (row: any, val: any) => {
					if (val >= 90) {
						return <span style="color: #30B08F">{val + '%'}</span>;
					} else if (val >= 70) {
						return <span style="color: #FEC171">{val + '%'}</span>;
					} else {
						return <span style="color: #C03639">{val + '%'}</span>;
					}
				},
			},
		],
		pagination: {
			pageNum: 1,
			// orderByColumn: 'visitCount',
			// isAsc: 'desc',
			// total: 0,
		},
		loading: false,
		disableOrderNumber: false,
	},
});
// 列表数据
const tableDatas = reactive<Record<string, TableOptionType[]>>({
	// 业务总览数据
	businessOverviewData: [],
	segmentOverviewData: [],
});
resizeMixins(chart); //echarts自适应窗口

initQuery(route.query, formData);
onMounted(() => {
	initChart();
});
onActivated(() => {});

// 格式化传过来的参数
function initQuery(query: anyObj, formData: FormModelType) {
	try {
		let data = JSON.parse(query.data);
		for (let key in data) {
			if (key === 'systemId') {
				formData[key] = data[key] + '';
			} else {
				formData[key] = data[key];
			}
			// formData[key] = data[key];
		}
	} catch {
		for (let key in query) {
			// formData[key] = query[key];

			if (key === 'systemId') {
				formData[key] = query[key] + '';
			} else {
				formData[key] = query[key];
			}
		}
	}
	if (formData.systemId) {
		formData.systemId += '';
	}
}

//表单初始化成功
function formInited() {
	systemTempName.value = myForm.value!.getLabel('systemId');
	searchHandler();
}

function formSearch() {
	initQuery(route.query, formData);
	searchHandler();
}

function formModalChange(opt: any) {
	console.log('formmodalchange');
	// 获取当前系统的名字
	if (opt.prop === 'systemId') {
		systemTempName.value = myForm.value!.getLabel('systemId');
	}
	if (opt.prop === 'businessCodeList') {
		queryBusinessOverview();
	}
	if (opt.prop === 'segmentIdList') {
		querySegmentOverview();
	}
}

//毫秒格式化
function formatter(val: any) {
	return toDecimalFormate(val, 'wm');
}
// //获取系统名称
function getSystemName() {
	systemName.value = systemTempName.value;
}

// 请求所有受搜索表单影响的数据
function searchHandler() {
	console.log('search---');
	tableConfigs.businessOverviewConfig.pagination!.pageNum = 1;
	tableConfigs.segmentOverviewConfig.pagination!.pageNum = 1;
	selectSystemId.value = formData.systemId;
	formDatas.businessFormData.businessCodeList = [];
	formDatas.segmentFormData.segmentIdList = [];
	//系统健康度图
	renderSystemHealthyRateChart();
	//告警类型占比图
	renderAlarmTypeProportionChart();
	//网端告警类型占比图
	renderSegmenetAlarmProportionChart();
	//请求趋势图数据并渲染趋势图
	querySystemTrendData();
	//请求业务总览数据
	queryBusinessOverview();
	//请求网端总览数据
	querySegmentOverview();
	// 获取系统名称
	getSystemName();

	// 请求业务和网端的数据
	businessForm.value?.setOptions('businessCodeList', formData.systemId);
	segmentForm.value?.setOptions('segmentIdList', formData.systemId);
}
// 初始化图表对象
function initChart() {
	chart.systemHealthyRateChart = echarts.init(document.getElementById('systemHealthyRateChartId') as HTMLElement);
	chart.alarmTypeProportionChart = echarts.init(document.getElementById('alarmTypeProportionChartId') as HTMLElement);
	chart.segmenetAlarmProportionChart = echarts.init(document.getElementById('segmenetAlarmProportionChartId') as HTMLElement);
	chart.systemReqCountTrendChart = echarts.init(document.getElementById('systemReqCountTrendChartId') as HTMLElement);
	chart.systemAvgDealTimeTrendChart = echarts.init(document.getElementById('systemAvgDealTimeTrendChartId') as HTMLElement);
	chart.systemHealthRateTrendChart = echarts.init(document.getElementById('systemHealthRateTrendChartId') as HTMLElement);
}
//重新设置图表宽高
// function chartResize() {
// 	chart.systemHealthyRateChart.resize();
// 	chart.alarmTypeProportionChart.resize();
// 	chart.segmenetAlarmProportionChart.resize();
// 	chart.systemReqCountTrendChart.resize();
// 	chart.systemAvgDealTimeTrendChart.resize();
// 	chart.systemHealthRateTrendChart.resize();
// }
// 渲染系统健康度
function renderSystemHealthyRateChart() {
	loading.systemHealthyRateChart = true;
	querySystemStatisticsDetail({
		systemId: formData.systemId,
		startTime: formData.startTime,
		endTime: formData.endTime,
		pageNum: 1,
		pageSize: 10,
	}).then((res: ApiResponse) => {
		loading.systemHealthyRateChart = false;
		// chart.systemHealthyRateChart.clear(); // 清除图表
		system.value = {}; // 清空字段对象
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			// if (res.code !== 1003) {
			// 	noDataOption(chart.systemHealthyRateChart, {
			// 		textStyle: { color: '#fff' },
			// 	});
			// 	return;
			// }
		}
		if (res.data.length === 0) {
			noDataOption(chart.systemHealthyRateChart, {
				textStyle: { color: '#fff' },
			});
			return;
		}
		// 无数据时显示
		system.value = res.data[0];
		let r = res.data[0] ? res.data[0] : {};
		console.log('[r.healthRate / 100, r.healthRate / 100]', [r.healthRate / 100, r.healthRate / 100]);

		// 有数据时显示
		systemHealthyRateOption.value = {
			title: {
				text: r.healthRate + '{a|%}',
				textStyle: {
					fontSize: 24,
					fontFamily: 'Microsoft Yahei',
					fontWeight: 'normal',
					color: '#ffffff',
					rich: {
						a: {
							fontSize: 24,
						},
					},
				},
				x: 'center',
				y: '40%',
			},
			graphic: [
				{
					type: 'group',
					left: 'center',
					top: '65%',
					children: [
						{
							type: 'text',
							z: 100,
							left: '10',
							top: 'middle',
							style: {
								fill: '#ffffff',
								text: '系统健康度',
								fontSize: 14,
							},
						},
					],
				},
			],
			series: [
				{
					type: 'liquidFill',
					radius: '65%',
					center: ['50%', '50%'],
					data: [r.healthRate / 100, r.healthRate / 100],
					backgroundStyle: {
						color: 'rgba(134, 228, 245, 0.2)',
					},
					outline: {
						borderDistance: 0,
						itemStyle: {
							borderWidth: 12,
							borderColor: {
								type: 'linear',
								x: 0,
								y: 0,
								x2: 0,
								y2: 1,
								colorStops: [
									{
										offset: 0,
										color: '#427ed7',
									},
									{
										offset: 0.5,
										color: '#66b5e7',
									},
									{
										offset: 1,
										color: '#85e2f5',
									},
								],
								globalCoord: false,
							},
						},
					},
					// 水波浪的颜色及透明度
					color: ['#49a5bf', '#34fdff'],
					itemStyle: {
						opacity: 0.8,
					},
					label: {
						show: false,
					},
					normal: {
						formatter: '',
					},
				},
			],
		};
		chart.systemHealthyRateChart.setOption(systemHealthyRateOption.value);
	});

	queryUserNum({
		systemId: formData.systemId,
		startTime: formData.startTime,
		endTime: formData.endTime,
		pageNum: 1,
		pageSize: 10,
	}).then((res: ApiResponse) => {
		userNum.value = res.data.userNum;
	});

	queryExceptionUserNum({
		systemId: formData.systemId,
		startTime: formData.startTime,
		endTime: formData.endTime,
		pageNum: 1,
		pageSize: 10,
	}).then((res) => {
		exceptionUserNum.value = res.data.exceptionUserNum;
	});
}
// 请求告警类型占比数据并渲染
function renderAlarmTypeProportionChart() {
	loading.alarmTypeProportionChart = true;
	queryAlarmProportion(formData).then((res: ApiResponse) => {
		loading.alarmTypeProportionChart = false;
		chart.alarmTypeProportionChart.clear();
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			// if (res.code !== 1003) {
			// 	noDataOption(chart.alarmTypeProportionChart, {
			// 		textStyle: { color: '#fff', formatter: '暂无告警数据~' },
			// 	});
			// 	return;
			// }
		}
		if (res.data.length == 0) {
			noDataOption(chart.alarmTypeProportionChart, {
				textStyle: { color: '#fff', formatter: '暂无告警数据~' },
			});
			return;
		}
		//有数据
		let alarmTypeProportions: any[] = [];
		res.data.forEach((element: any) => {
			if (element.alarmCount > 0) {
				alarmTypeProportions.push({
					alarmTypeId: element.alarmTypeId,
					name: element.alarmTypeName,
					value: element.alarmCount,
				});
			}
		});
		const chartIns = chart.alarmTypeProportionChart;
		renderProportionChart(chartIns, alarmTypeProportions, '告警类型占比');
	});
}
// 请求网端告警量占比数据并渲染
function renderSegmenetAlarmProportionChart() {
	loading.segmenetAlarmProportionChart = true;
	//请求数据
	querySegmentAlarmProportion(formData).then((res: ApiResponse) => {
		loading.segmenetAlarmProportionChart = false;
		chart.segmenetAlarmProportionChart.clear();
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			// if (res.code !== 1003) {
			// 	noDataOption(chart.segmenetAlarmProportionChart, {
			// 		textStyle: { color: '#fff', formatter: '暂无告警数据~' },
			// 	});
			// 	return;
			// }
		}
		if (res.data.length == 0) {
			noDataOption(chart.segmenetAlarmProportionChart, {
				textStyle: { color: '#fff', formatter: '暂无告警数据~' },
			});
			return;
		}
		//有数据,根据请求结果重新封装数组
		let segmentAlarmProportions: any[] = [];
		res.data.forEach((element: any) => {
			if (element.alarmCount > 0) {
				segmentAlarmProportions.push({
					id: element.id,
					name: element.segmentName,
					value: element.alarmCount,
				});
			}
		});
		const chartIns = chart.segmenetAlarmProportionChart;
		//渲染图表
		renderProportionChart(chartIns, segmentAlarmProportions, '网端告警量占比');
	});
}
// 公共方法:渲染比例图表
function renderProportionChart(chartIns: any, valueArr: any, title: any) {
	// 有数据
	chartIns.setOption({
		// 调色盘
		color: ['#fe5578', '#ff7d4f', '#6f81f7', '#1dc69d', '#00ffff', '#e5ba43', '#25b2ff', '#13eecc'],
		// 悬浮提示
		tooltip: {
			trigger: 'item',
			formatter: '{b}：{d}%',
			confine: true,
		},
		series: [
			{
				name: '占比',
				type: 'pie',
				minAngle: 12,
				radius: ['30%', '45%'],
				center: ['50%', '50%'],
				avoidLabelOverlap: true,
				// 标签文本
				label: {
					formatter: function (params: any) {
						var percent = params.percent + '%';
						var params = params.name;
						var newParamsName = '';
						var paramsNameNumber = params.length;
						var provideNumber = 4;
						var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
						if (paramsNameNumber > provideNumber) {
							for (var p = 0; p < rowNumber; p++) {
								var tempStr = '';
								var start = p * provideNumber;
								var end = start + provideNumber;
								if (p == rowNumber - 1) {
									tempStr = params.substring(start, paramsNameNumber);
								} else {
									tempStr = params.substring(start, end) + '\n';
								}
								newParamsName += tempStr;
							}
						} else {
							newParamsName = params;
						}
						return newParamsName + '\n' + percent;
					},
					top: 100,

					/*formatter: "{b}\n{da| {d}%}",
				rich: {
				  da: {
					color: "#ffffff",
				  },
				},
				width: 20,
				overflow: "truncate"*/
				},
				// 标签线
				labelLine: {
					length: 20,
					length2: 20,
					lineStyle: {
						type: 'dashed',
					},
				},
				// 高亮状态
				emphasis: {
					label: {
						show: true,
						fontSize: '14',
						fontWeight: 'bold',
					},
				},
				data: valueArr,
			},
		],
	});
}
// 请求趋势图数据并渲染趋势图
function querySystemTrendData() {
	querySystemTrendList(formData).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			// if (res.code !== 1003) {
			// 	noDataOption(chart.systemReqCountTrendChart, {
			// 		textStyle: { color: '#ffffff' },
			// 	});
			// 	noDataOption(chart.systemAvgDealTimeTrendChart, {
			// 		textStyle: { color: '#ffffff' },
			// 	});
			// 	noDataOption(chart.systemHealthRateTrendChart, {
			// 		textStyle: { color: '#ffffff' },
			// 	});
			// 	return;
			// }
		}
		if (!res.data.trendData || res.data.trendData.resLabelTimeArr.length <= 0) {
			noDataOption(chart.systemReqCountTrendChart, {
				textStyle: { color: '#fff' },
			});
			noDataOption(chart.systemAvgDealTimeTrendChart, {
				textStyle: { color: '#fff' },
			});
			noDataOption(chart.systemHealthRateTrendChart, {
				textStyle: { color: '#fff' },
			});
			return;
		}

		const resData = res.data.trendData;
		//历史峰值
		reqPeek.value = resData.resFieldMap?.avgAndPeakVo || {};
		for (let key in reqPeek.value) {
			if (reqPeek.value[key] === null || reqPeek.value[key] === 'null') {
				reqPeek.value[key] = 0;
			}
		}
		// 各趋势图的数据集

		labelTimeArr.value = resData.resLabelTimeArr;
		const healthRateCount = resData.resFieldMap.healthRateList;
		const reqCountCount = resData.resFieldMap.reqCountList;
		const responseTimeCount = resData.resFieldMap.avgServerResponseTimeList.map((t: any) => t / 1000);
		// 渲染系统请求量趋势图
		renderTrendChart('systemReqCountTrendChart', resData.resPointTimeRangeArr, reqCountCount, '系统请求量', 'rgb(40,238,239)');
		//渲染系统平均响应时长趋势图
		renderTrendChart('systemAvgDealTimeTrendChart', resData.resPointTimeRangeArr, responseTimeCount, '平均响应时长', 'rgb(255,125,77)');
		//渲染系统健康度趋势图
		renderTrendChart('systemHealthRateTrendChart', resData.resPointTimeRangeArr, healthRateCount, '系统健康度', 'rgb(30,199,154)');
		echarts.connect([chart.systemReqCountTrendChart, chart.systemAvgDealTimeTrendChart, chart.systemHealthRateTrendChart]);
	});
}
//公共方法:渲染趋势图
function renderTrendChart(trendType: any, toolTipArr: any, yData: any, title: any, seriesColor: any) {
	const chartIns = chart[trendType];
	chartIns.clear();
	if (yData.length == 0) {
		noDataOption(chartIns, {
			textStyle: { color: '#fff', formatter: '暂无告警数据~' },
		});
		return;
	}
	// 有数据
	chartIns.setOption({
		// 坐标系
		grid: {
			containLabel: true,
			x: 20,
			x2: 20,
			y: 10,
			y2: 15,
		},
		// 字体样式
		textStyle: {
			color: '#ffffff',
		},
		// 提示框
		tooltip: {
			trigger: 'axis',
			formatter: function (params: any) {
				let label = toolTipArr[params[0].dataIndex][0] + '～' + toolTipArr[params[0].dataIndex][1] + '<br/>';
				params.forEach((item: any, index: number) => {
					label +=
						'<i style="display:inline-block;width:10px;height:10px;background:' +
						item.color +
						';margin-right:5px;border-radius:50%;}"></i><span style="width:90px;display:inline-block;">' +
						item.seriesName +
						'</span> ' +
						item.value;
				});
				if (trendType == 'systemHealthRateTrendChart') {
					label += '%';
				}
				if (trendType == 'systemAvgDealTimeTrendChart') {
					let tiplabel = toolTipArr[params[0].dataIndex][0] + '～' + toolTipArr[params[0].dataIndex][1] + '<br/>';
					params.forEach((item: any, index: any) => {
						tiplabel +=
							'<i style="display:inline-block;width:10px;height:10px;background:' +
							item.color +
							';margin-right:5px;border-radius:50%;}"></i><span style="width:90px;display:inline-block;">' +
							item.seriesName +
							'</span> ' +
							toDecimalFormate(item.value);
					});
					return tiplabel;
				}
				return label;
			},
		},
		// x轴
		xAxis: {
			type: 'category',
			data: labelTimeArr.value,
			boundaryGap: false,
			...chartStyle.xAxisStyle,
		},
		// y轴
		yAxis: {
			type: 'value',
			splitNumber: 5,
			// minInterval: 1,
			axisLabel: {
				margin: 5,
			},
			max: function () {
				if (title == '系统健康度') {
					return 100;
				}
			},
			...chartStyle.yAxisStyle,
		},
		// 数据
		series: [
			{
				name: title,
				type: 'line',
				data: yData,
				symbol: 'none',
				itemStyle: {
					color: seriesColor,
				},
				// 填充区域
				areaStyle: {
					color: {
						type: 'linear',
						x: 0,
						x2: 0,
						y: 0,
						y2: 1,
						colorStops: [
							{
								offset: 0,
								color: 'rgba(' + seriesColor.substring(seriesColor.indexOf('(') + 1, seriesColor.indexOf(')')) + ',0.4)',
							},
							{
								offset: 1,
								color: 'rgba(' + seriesColor.substring(seriesColor.indexOf('(') + 1, seriesColor.indexOf(')')) + ',0)',
							},
						],
					},
				},
			},
		],
	});
}
// 获取业务总览列表数据
function queryBusinessOverview() {
	tableConfigs.businessOverviewConfig.loading = true;
	queryBusinessOverviewListPage({
		...formData,
		...formDatas.businessFormData,
	}).then((res: ApiResponse) => {
		tableConfigs.businessOverviewConfig.loading = false;
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			// if (res.code !== 1003) {
			// 	return;
			// }
		}
		let pagination = tableConfigs.businessOverviewConfig!.pagination;
		tableDatas.businessOverviewData = res.data.data;
		pagination!.total = res.data.total;

		downloadStartTime.value = formData.startTime;
		downloadEndTime.value = formData.endTime;
		if (pagination && (pagination.total as number) <= 0) {
			exportDisable.value = true;
		} else {
			exportDisable.value = false;
		}
	});
}
// 导出业务总览列表数据
function handleBusiExport() {
	const d = JSON.parse(JSON.stringify(formData));
	d.businessCodeList = formDatas.businessFormData.businessCodeList;
	d.isAsc = formDatas.businessFormData.isAsc;
	d.orderByColumn = formDatas.businessFormData.orderByColumn;
	d.pageNum = undefined;
	d.pageSize = undefined;
	d.startTime = downloadStartTime.value;
	d.endTime = downloadEndTime.value;
	downloading.value = true;
	exportBusinessList(d).then((res) => {
		downloading.value = false;
		downloadFromBlob(res, '业务概况列表').then((o: any) => {
			if (!o.flag) {
				proxy?.$message.warning(o.msg);
			}
		});
	});
}
// 获取网端总览列表数据
function querySegmentOverview() {
	tableConfigs.segmentOverviewConfig.loading = true;
	let params = {
		...formDatas.segmentFormData,
		startTime: formData.startTime,
		endTime: formData.endTime,
		systemId: formData.systemId,
	};
	querySegmentDataOverview(params).then((res: ApiResponse) => {
		tableConfigs.segmentOverviewConfig.loading = false;
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			// if (res.code !== 1003) {
			// 	return;
			// }
		}
		let pagination = tableConfigs.segmentOverviewConfig.pagination;
		pagination!.total = res.data.total;
		tableDatas.segmentOverviewData = res.data.data;
		if (pagination && pagination.total! <= 0) {
			exportDisable1.value = true;
		} else {
			exportDisable1.value = false;
		}
	});
}
// 导出网端总览列表数据
function handleExportSegment() {
	const d = JSON.parse(
		JSON.stringify({
			...formData,
			...formDatas.segmentFormData,
		})
	);
	d.pageNum = undefined;
	d.pageSize = undefined;
	d.systemName = systemName.value;
	d.startTime = downloadStartTime.value;
	d.endTime = downloadEndTime.value;
	downloading1.value = true;
	exportSegmentList(d).then((res: ApiResponse) => {
		downloading1.value = false;
		downloadFromBlob(res, '系统网端总览列表').then((o: any) => {
			if (!o.flag) {
				proxy?.$message.warning(o.msg);
			}
		});
	});
}

// 系统健康度请求量跳转基础告警归并分析
function handleAlarmValJump(val: any) {
	router.push({
		path: '/business-monitor/monitor-analysis/basic-alarm-merging-analysis',
		query: {
			data: JSON.stringify({
				systemId: selectSystemId.value,
				startTime: formData.startTime,
				endTime: formData.endTime,
				alarmState: [val],
			}),
		},
	});
}
//当前用户数跳转用户操作回溯分析
function go2UserOperate(val?: any) {
	router.push({
		path: '/business-monitor/monitor-analysis/user-operate-analysis',
		query: {
			data: JSON.stringify({
				systemId: formData.systemId,
				startTime: formData.startTime,
				endTime: formData.endTime,
				userStatus: val === 1 ? 0 : undefined,
			}),
		},
	});
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@mixin title-box {
	display: flex;
	align-items: center;
}
.style-split-yd-card {
	padding-bottom: 10px;
}
.system-health-textBox {
	display: flex;
	align-items: center;
	height: 84%;
	.vertical-center {
		width: 100%;
	}
	.system-health-item {
		color: #2beded;
		font-size: 14px;
		margin-bottom: 8px;
	}
	.text-white {
		color: #ffffff;
	}
	.text-red {
		color: #fe5578;
	}
	.text-yellow {
		color: #ff7d4f;
	}
	.text-blue {
		color: #2beded;
	}
}
.alarm-pie-title {
	height: 13%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #ffffff;
	font-size: 18px;
	font-weight: bold;
}

.icon-cls {
	width: 20px;
	height: 20px;
	color: #00ffff;
}
:deep(.el-form-item--default) {
	margin-bottom: 0;
}
</style>
